package com.vishop.controllers;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.vishop.models.Winkelwagen;
import com.vishop.services.BestellingService;
import com.vishop.services.PersoonService;
import com.vishop.services.ProductService;


@Controller
@SessionAttributes("winkelwagen")
public class WinkelwagenController
{
	@Autowired
	private BestellingService bestellingService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private PersoonService persoonService;
	
	@ModelAttribute("winkelwagen")
	public Winkelwagen createWinkelwagen()
	{
		return new Winkelwagen();
	}
	
	@RequestMapping(value="/winkelwagen-overzicht", method=RequestMethod.GET)
	public ModelAndView getWinkelwagen(@ModelAttribute("winkelwagen")Winkelwagen winkelwagen){
		ModelAndView mav = new ModelAndView("winkelwagen");
		
		mav.addObject("winkelwagen", winkelwagen);
		
		return mav;
	}
	
	@RequestMapping(value="/winkelwagen", method=RequestMethod.POST)
	public String optionsWinkelwagen(@RequestParam(value="maakleeg", required=false) String maakLeeg, @RequestParam(value="bestel", required=false) String bestel, @ModelAttribute("winkelwagen")Winkelwagen winkelwagen){
		
		String redirect = "redirect:/winkelwagen-overzicht.htm";
		System.out.println("start legen: "+maakLeeg);
		
		if(maakLeeg != null && maakLeeg.equals("legen")){ winkelwagen.getProducten().clear();}	
		else if(bestel != null){ redirect = "redirect:/bestelling.htm";}
		
		return redirect;
	}
	
	@RequestMapping(value="/winkelwagen", method=RequestMethod.GET)
	public String editWinkelwagen(	@RequestParam(value="id", required=false) Long id,
									@RequestParam(value="cat", required=false) String cat, 
									@RequestParam(value="-id", required=false) Long delId,
									@ModelAttribute("winkelwagen")Winkelwagen winkelwagen)
	{
		String redirect = "redirect:/winkelwagen-overzicht.htm";
		
		//zet product in winkelwagen
		if(id != null) { winkelwagen.getProducten().add(productService.getById(id.intValue())); }
		if(delId != null) { winkelwagen.removeProduct(delId); }
		
		// redirect naar juiste path
		if(cat != null)
		{
			redirect = cat.equals("heren")? "redirect:/heren.htm" : "redirect:/dames.htm";
		}
		
		return redirect;
	}
	
}
